package com.course.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.course.db.ConnectDB;

public class ExecuteDB extends ConnectDB {
	
	//
	private Connection dbConn;
	private Statement stmt;
	private ResultSet rs;
	
    //error info
    private String errMes;

	//Constructor
	public ExecuteDB()
	{
		System.out.println("hello createConnection");
		dbConn = super.getConn();
		System.out.println("createConnection Ok!");
		stmt = null;
		rs = null;
		this.errMes = super.getErrMes();
	}

	 //excute update sql 
	public boolean exeSql(String strSql)
	{
		System.out.println("hello exeSql");
		boolean isSuc = false;
		try
		{
			//System.out.println(strSql);
   			stmt=dbConn.createStatement();
			stmt.executeUpdate(strSql);

			System.out.println("before statement close");
			stmt.close();
			System.out.println("after statement close");
			isSuc = true;
		}
		catch(Exception e)
		{
			System.out.println("exception:"+strSql);
			this.errMes = this.errMes + "<br>" +e.toString();
			
		}
		return isSuc;
	}

	//excute query sql
    public ResultSet exeQuery(String strSql)
	{
    	System.out.println("hello exeQuery");
		try
		{
   			stmt=dbConn.createStatement();
   			System.out.println(strSql);
			rs =stmt.executeQuery(strSql);
		}
		catch(Exception e)
		{
            this.errMes = this.errMes + "<br>" +e.toString();
			rs = null;
		}
		return rs;
	}
    
    public void close_all()
    {
    	if(rs!=null)
    	{
    		try{
    			rs.close();
    		}catch(SQLException el){
    			el.printStackTrace();
    		}
    	}
    	if(stmt != null){
    		try{
    			stmt.close();
    		}catch(SQLException el){
    			el.printStackTrace();
    		}
    	}
    	if(dbConn != null){
    		try{
    			dbConn.close();
    		}catch(SQLException el){
    			el.printStackTrace();
    		}
    	}
    }

    //erro msh
    public String getErrMes()
    {
        return errMes;
    }

}
